package com.iflysse.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.auth0.jwt.interfaces.Claim;
import com.iflysse.consts.ResultEnum;
import com.iflysse.dao.AccountDao;
import com.iflysse.entity.Account;
import com.iflysse.ex.CommonException;
import com.iflysse.utils.JwtUtil;

/**
 * JWT登录认证拦截器
 * @author oubijie
 *
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

	private final static Log log = LogFactory.getLog(TokenInterceptor.class);
	
    @Autowired
    private AccountDao accountDao;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

       String token= request.getHeader("token");
        log.info("token信息为："+token);
        //校验token是否为空
        if(token==null){
        	throw new CommonException(ResultEnum.NOTOKEN.getCode(), ResultEnum.NOTOKEN.getMsg());
        }

        //校验token是否合法
        Map<String, Claim> map= JwtUtil.parseToken(token);
        log.info("token解析成map后结果："+map);
        if(map==null||map.size()==0){
        	throw new CommonException(ResultEnum.TOKENERROR.getCode(), ResultEnum.TOKENERROR.getMsg());
        }

        //校验token是否正确 获取userId和role
        String userId= map.get("userId").asString();
        String role= map.get("role").asString();

        Account account = accountDao.findUserByAccountIdAndRole(userId, role);
        if (account != null){
        	request.setAttribute("LoginUser", account);
            return true;
        }else{
            log.error("token信息有误，token:"+token);
            throw new CommonException(ResultEnum.TOKENERROR.getCode(), ResultEnum.TOKENERROR.getMsg());
        }
    }
}
